// 如果以前引入过模块,那么他再次引入,其实是引入的缓存
//始终是1次,因为前面引入过了
import express from "express";
import DB from "./../../libs/DBHelper"
import multer from "multer";
import fs from "fs";

const multerObj = multer({
    dest: "./upload"
})
//1.创建保安 (高新聘请)
let apiRouter = express.Router();
//2.给保安大爷 安排 管理任务

apiRouter.post("/login", (request, response, next) => {
    var prams = [request.body.uname, request.body.upwd];
    var loginSql = "select `u_id`,`u_name`,`u_type`,`u_email` from usersinfo where u_name=? and u_pwd=?;";
    console.log(prams);
    DB.exec(loginSql, prams, function (err, row) {
        if (err) {
            response.json({
                msg: err.message,
                status: -2
            })
        }
        if (row.length >= 1) {
            //登录成功,就把当前登录着的信息保存到session
            // session  能做什么? 用于在服务器端的 页面之间传值
            request.session["isLogin"] = row[0];
            response.json({
                msg: "登录成功",
                status: 1,
                data: row[0]
            })
        } else {
            response.json({
                msg: "登录失败",
                status: -1,
            })
        }
    })

})


apiRouter.post("/upload", multerObj.any(), (request, response, next) => {
    response.end("ok");
})

//3.检测用户名是否存在的接口
apiRouter.get("/checkuser", async (request, response, next) => {
    let checkSql = "SELECT * FROM usersinfo WHERE u_name=?;";
    let params = [request.query.uname];
    //await只能卸载 带有 async的函数内部  ES7  async/await
    // 解决异步
    var res = await DB.execAsync(checkSql, params);
    if (res.length >= 1) {
        response.end("true");
    } else {
        response.end("ok");
    }
})

//4.注册逻辑
apiRouter.post("/reg", function (request, response, next) {
    //1.准备sql语句
    let regSQL = "INSERT INTO `usersinfo` (`u_name`,`u_pwd`)VALUES(?,?);";
    //2.准备参数
    var params = [request.body.uname, request.body.upwd];
    console.log(params)
    //3.执行sql语句.得到结果
    DB.exec(regSQL, params, (err, result, fields) => {
        if (err) {
            // console.log(err)
            response.json({
                msg: "注册异常",
                err: err.message,
                status: -3
            });
            return;
        }
        if (result.affectedRows == 1) {
            response.json({
                msg: "注册成功",
                status: 2,
            })
        } else {
            response.json({
                msg: "注册失败",
                status: -2,
            })
        }

    })
    // try {
    //     var res = await DB.execAsync(regSQL, params);
    //     if (res.affectedRows == 1) {
    //         response.json({
    //             msg: "恭喜您,注册成功!",
    //             status: 2
    //         })
    //     } else {
    //         response.json({
    //             msg: "注册失败!",
    //             status: -2
    //         })
    //     }
    // } catch (err) {
    //     response.json({
    //         msg: "注册异常",
    //         status: -3
    //     })
    // }
})

//5.产品列表
apiRouter.get("/products", async (request, response, next) => {
    var productStr = fs.readFileSync("./data/list.json").toString();
    response.end(productStr);
})

//6.通过产品id,获得产品详细信息
apiRouter.get("/getproduct", async (request, response, next) => {
    var productStr = fs.readFileSync("./data/list.json").toString();
    let productObj = JSON.parse(productStr);

    var resData = productObj.filter((el) => {
        return el.p_id == request.query.id
    })
    // response.json(对象)
    response.json(resData);
})

//7.加入购物车逻辑
apiRouter.post("/addCart", async (request, response, next) => {
    //1.准备sql语句
    let queryCart = "SELECT*FROM `carts`  WHERE u_id=? AND p_id=? AND c_status=1;";
    //2.前端请求的数据
    let queryParams = [request.body.uid, request.body.pid];
    console.log(queryParams)
    //3.根据同步异步得模块获取数据
    var res = await DB.execAsync(queryCart, queryParams);
    console.log(res)
    //4.判断
    if (res.length >= 1) {
        //已经买过该商品，在数据库直接修改数量即可
        var updateCart = "UPDATE carts SET c_num=c_num + ?,c_total=c_price*c_num WHERE u_id=? AND p_id=? AND c_status=1;";
        let updateParams = [
            request.body.cnum,
            request.body.uid,
            request.body.pid
        ]

        let res = await DB.execAsync(updateCart, updateParams);
        if (res.affectedRows == 1) {
            response.json({
                msg: "加入购物车成功u",
                status: 5
            })
        } else {
            response.json({
                msg: "加入购物车失败u",
                status: -5
            })
        }
    } else {
        //没有购买过同样的商品
        let insertCart = "INSERT  INTO `carts` (`p_id`,`u_id`,`c_name`,`c_num`,`c_price`,`c_total`,`c_img`)VALUES(?,?,?,?,?,?,?);";

        let insertParams = [
            request.body.pid,
            request.body.uid,
            request.body.cname,
            request.body.cnum,
            request.body.cprice,
            request.body.cnum * request.body.cprice,
            request.body.cimg
        ]

        var res = await DB.execAsync(insertCart, insertParams);
        if (res.affectedRows == 1) {
            response.json({
                msg: "加入购物车成功 i",
                status: 4
            })
        } else {
            response.json({
                msg: "加入购物车失败 i",
                status: -4
            })
        }
    }
})

//8.获取购物车列表
apiRouter.get("/getCart", async (request, response, next) => {
    let sql = "SELECT * FROM carts WHERE u_id=? and c_status=1";
    let params = [request.query.uid];

    var res = await DB.execAsync(sql, params);

    var resObj = {
        status: 6,
        data: res,
        msg: "获取成功"
    }

    if (res.length == 0) {
        resObj["status"] = "-6";
        resObj["data"] = "null";
        resObj["msg"] = "获取失败"
    }
    response.json(resObj);
})

//9.修改购物车商品得信息
apiRouter.post("/modify", async (request, response, next) => {
    let sql = "UPDATE carts SET c_num=?,c_total=c_price*c_num WHERE u_id=? AND p_id=? AND c_status=1;"

    let params = [
        request.body.cnum,
        request.body.uid,
        request.body.pid
    ]

    var res = await DB.execAsync(sql, params);
    if (res.affectedRows == 1) {
        response.json({
            msg: "修改购物车成功",
            status: 7,
        })
    } else {
        response.json({
            msg: "修改购物车失败",
            status: -7,
        })
    }
})

//10.删除购物车
apiRouter.post("/delete", async (request, response, next) => {
    let sql = "UPDATE carts SET c_status=0 WHERE c_id=? AND c_status=1;"
    let params = [
        request.body.cid
    ]

    var res = await DB.execAsync(sql, params);
    if (res.affectedRows == 1) {
        response.json({
            msg: "删除成功",
            status: 8
        })
    } else {
        response.json({
            msg: "删除失败",
            status: -8
        })
    }
})

//11.删除购物车中所有得商品
apiRouter.post("/deleteAll", async (request, response, next) => {
    let sql = "UPDATE carts SET c_status=0 WHERE u_id=? AND c_status=1;"
    let params = [
        request.body.uid
    ]

    var res = await DB.execAsync(sql, params);
    if (res.affectedRows == 1) {
        response.json({
            msg: "删除成功",
            status: 10
        })
    } else {
        response.json({
            msg: "删除失败",
            status: -10
        })
    }
})

//12.实时查看购物车得商品数量
apiRouter.get("/getCunt", async (request, response, next) => {
    let sql = "SELECT SUM(c_num) AS totals FROM `carts` WHERE c_status=1 AND u_id=?;"
    let params = [
        request.query.uid
    ]
    console.log(params)
    var res = await DB.execAsync(sql, params)
    console.log(res);
    response.json({
        count: res[0].totals
    })
})

//13.退出登录
apiRouter.get("/quit", async (request, response, next) => {
    //把session设置成空
    request.session = "";
    //服务器命令浏览器清除cookie
    response.clearCookie("tokenUser");
    response.send("<script>alert('退出成功!')</script>")
})

//暴露 保安大爷,去干活
module.exports = {
    apiRouter
}